<?

class Smutty_Config {

	var $data;

	/**
	 *  constructor
	 *
	 */

	function Smutty_Config() {
		$this->data = array();
	}

	/**
	 *  loads the config from the specified file
	 *
	 *  @param [path] path to file to load
	 *
	 */

	function loadConfig( $path ) {
		if ( !$f = @fopen($path,'r') )
			new Smutty_Exception( 'config file not found: ' . $path, 'SmuttyConfig' );
		while ( $line = fgets($f) )
			$this->loadLine( chop($line) );
		fclose( $f );
	}

	/**
	 *  processes a single line of configuration info
	 *
	 *  @param [line] the line to parse
	 *
	 */

	function loadLine( $line ) {
		if ( substr($line,0,1) == '#' )
			next; // skip comments
		// break the line into name and value
		preg_match( '/^([\w_\.]*\*{0,1})\s*=\s*([\d\w\/_:]*\s*)/', $line, $matches );
		$name = trim( $matches[1] );
		$value = trim( $matches[2] );
		if ( $name && value )
			$this->data[ $name ] = $value;
	}

	/**
	 *  looks for a config setting matching the given
	 *  name.  you can use a "*" as a wildcard
	 *
	 *  @param [name] setting name
	 *  @param String/array
	 *
	 */

	function get( $name ) {

		// are we looking to for multiple matches?
		if ( strpos($name,'*') ) {
			$vars = array();
			$regexp = $this->_getWildcardRegExp( $name );
			foreach ( $this->data as $key => $value )
				if ( preg_match($regexp,$key) )
					$vars[ $key ] = $value;
			return $vars;
		}

		// else check for an exact match
		elseif ( $value = $this->data[$name] )
			return $value;

		// lastly, check for wildcards in the spec
		// eg. route.ctlr.prefix* = whatever
		else foreach ( $this->data as $key => $value ) {
			$regexp = $this->_getWildcardRegExp( $key );
			if ( preg_match($regexp,$name) )
				return $value;
			}

	}

	/**
	 *  converts a string into a regexp where wilcards (*'s)
	 *  will be matches in it.
	 *
	 *  @param [name] the string to convert
	 *  @return String
	 *
	 */

	function _getWildcardRegExp( $name ) {

		$regexp = '/^' . preg_replace('/\./','\\.',$name) . '$/';
		$regexp = preg_replace( '/\*/','.*', $regexp );

		return $regexp;

	}

	/**
	 *  returns the singleton for this object
	 *
	 *  @return Smutty_Config
	 *
	 */

	function getInstance() {
		static $instance;
		if ( $instance == null ) {
			$instance = new Smutty_Config();
			$instance->loadConfig( 'library/smutty.cfg' );
			$instance->loadConfig( 'application/app.cfg' );
		}
		return $instance;
	}

}

?>
